package com.bw.hxc.controller;


import com.bw.hxc.entity.Authority;
import com.bw.hxc.entity.Result;
import com.bw.hxc.entity.User;
import com.bw.hxc.service.IAuthorityService;
import com.bw.hxc.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黄旭超
 * @since 2022-05-26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IAuthorityService authorityService;

    @RequestMapping("loginOk")
    public Result loginOk(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();//获取用户名
        if (principal instanceof UserDetails){
            return new Result(200,"登录成功",principal);
        }else {
            return new Result(201,"登录失败","");
        }
    }

    @RequestMapping("loginFailed")
    public Result loginFailed(){
        return new Result(202,"用户登录失败","");
    }

    /**
     * 要求用户登录
     * @return
     */
    @RequestMapping("noLogin")
    public ResponseEntity noLogin(){
        return new ResponseEntity(new Result(300,"用户尚未登录","登录"),HttpStatus.FORBIDDEN);
    }

    @RequestMapping("save")
    public Result save (@RequestBody User user){
        userService.saveOrUpdate(user);
        Authority authority = new Authority();
        authority.setUsername(user.getUsername());
        authority.setAuthority("USER");
        authorityService.saveOrUpdate(authority);
        return new Result(200,"注册","注册成功");
    }





}
